//提成发放列表table
var $royaltyMoneyTableList = $('#royaltyMoneyTable');
var $sendRoyaltyTableList = $('#updateSendRoyaltyTable');
var productOrderId=sessionStorage.getItem('productOrderId');
var abs = new verjs_select();
$(function () {
    $('#inputTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
    });
    getReturnMoneyList();

    getOrderProductList();

    getUpdateSendRoyaltyList();


    $('#addInputMoney').on('show.bs.modal', function () {
        $(this).find('.modal-dialog').draggable();
    }).on('hidden.bs.modal', function () {
        $(this).find('.modal-dialog').css({
            left: 0,
            top: 0
        });
    })
})

function getTel() {
    var data = $("#productName option:selected").attr("data");
    $("#productPrice").val(data);
}

function getOrderProductList(customerProductId) {
    var orderId = $("#orderCode").val();
    $.getJSON("/order/financeOrderProductAndActivity?productOrderId="+orderId, function (data) {
        if (data.code == '000000') {
            var optionHtml = '';
            var optionArr = data.data;
            var optionSelected = $('#companySelect option:selected').val();
            //公司搜索条件下拉框
            var searchCompanyOptionHtml = '<option value="">请选择产品名称</option>';
            optionArr.map(function (item, index) {
                if (customerProductId && customerProductId == item.customerProductId){
                    searchCompanyOptionHtml += '<option value="' + item.customerProductId + '" data="' + item.money + '" selected>' + item.productName + '</option>';
                }else {
                    searchCompanyOptionHtml += '<option value="' + item.customerProductId + '" data="' + item.money + '">' + item.productName + '</option>';
                }
            });
            $('#productName').html(searchCompanyOptionHtml);
            var selectDate = [];
            for (var i = 0, len = data.data.length; i < len; i++) {
                var company = data.data[i];
                var selectCompany = {};
                selectCompany.id = company.customerProductId;
                selectCompany.name = company.productName;
                selectDate.push(selectCompany);
            }
            /*abs.render({
                elem: "#search",
                data: selectDate,
                init_value: [1],
                body_height: 300,
                checkbox: true,
                name: "test"
            });*/
            $('#searchoption-list').css('z-index',1000);
            /*$('#productName').selectpicker({
                sanitize: true,
                size: 8
            });*/
        }
    });
}

//表格接口传参
function logQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.orderId = $("#orderCode").val();
    return params;
}


//表格接口传参
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.productOrderId = sessionStorage.getItem('productOrderId');
    return params;
}

//表格批次
function indexFormat(value, row, index) {
    return index + 1;
}

//提成发放表格
function getReturnMoneyList() {
    //先销毁表格
    $royaltyMoneyTableList.bootstrapTable('destroy');
    $royaltyMoneyTableList.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/financeOrderProductAndActivity',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'returnMoneyId',
        idField: 'returnMoneyId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'productOrderId',visible: false},
            {title: '产品号', field: 'finishOrderProductId',visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '产品名称', field: 'productName', sortable: false,align: 'left', valign: 'middle'},
            {title: '产品售价', field: 'money', sortable: false,align: 'left', valign: 'middle'},
            {title: '业绩金额', field: 'scoreMoney', sortable: false,align: 'left', valign: 'middle'},
            {title: '业绩换算比例',field: 'scoreConvertRatio', sortable: false,align: 'left', valign: 'middle'},
            {title: '应发放提成',field: 'royaltyMoney', sortable: false,align: 'left', valign: 'middle'},
            {title: '提成录入人', field: 'inputUserName', sortable: false,align: 'left', valign: 'middle'},
            {title: '录入时间', field: 'inputTime', sortable: false, align: 'left',valign: 'middle'},
            {title: '操作', field: 'operationThing',  align: 'left',valign: 'middle',formatter: enterPayMent}, //,formatter: enterPayMent

        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                var amountTotal=0,commissionTotal=0,releaseTime;
                for(let i=0,len=result.data.length;i<len;i++){
                    amountTotal+=Number(result.data[i].scoreMoney)
                    commissionTotal+=Number(result.data[i].royaltyMoney)

                }
                // console.log(amountTotal,commissionTotal)
                $("#amountTotalspan").html(amountTotal)
                $("#commissionTotalspan").html(commissionTotal)
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            // $('#customerProductTableList').css({
            //     minWidth: $('#customerProductTableList').width()
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            //     /*onResize: function () {
            //     }*/
            // });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });

}

//提成发放修改记录表格
function getUpdateSendRoyaltyList() {
    //先销毁表格
    $sendRoyaltyTableList.bootstrapTable('destroy');
    $sendRoyaltyTableList.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/sendRoyaltyLog/selectSendRoyaltyLogList',//请求地址
        method: 'POST',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'orderSendRoyaltyLogId',
        idField: 'orderSendRoyaltyLogId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: logQueryParams,//查询参数
        columns: [
            {title: '主键', field: 'orderSendRoyaltyLogId',visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '提成发放id', field: 'chsOrderSendRoyaltyId', sortable: false,align: 'left', valign: 'middle'},
            {title: '产品名称', field: 'productName', sortable: false,align: 'left', valign: 'middle'},
            {title: '修改前提成发放金额', field: 'formerMoney', sortable: false,align: 'left', valign: 'middle'},
            {title: '修改后提成发放金额', field: 'newMoney', sortable: false,align: 'left', valign: 'middle'},
            {title: '操作人',field: 'createPeopleName', sortable: false,align: 'left', valign: 'middle'},
            {title: '操作时间',field: 'createTm', sortable: false,align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                var amountTotal=0,commissionTotal=0,releaseTime;
                for(let i=0,len=result.data.length;i<len;i++){
                    amountTotal+=Number(result.data[i].scoreMoney)
                    commissionTotal+=Number(result.data[i].royaltyMoney)

                }
                // console.log(amountTotal,commissionTotal)
                $("#amountTotalspan").html(amountTotal)
                $("#commissionTotalspan").html(commissionTotal)
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            // $('#customerProductTableList').css({
            //     minWidth: $('#customerProductTableList').width()
            // }).colResizable({
            //     resizeMode: 'overflow',
            //     liveDrag: true,
            //     gripInnerHtml: "<div class='grip'></div>",
            //     draggingClass: "dragging",
            //     disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
            //     postbackSafe: true,                                         // 刷新后保持拖动的宽度
            //     partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
            //     flush: true,
            //     minWidth: 80,
            //     /*onResize: function () {
            //     }*/
            // });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });

}


function royaltyBtn() {

    // var returnMoneyId = $.trim($('#returnMoneyIdHide').val());//回款id
    var productName = $.trim($('#productName').val());//产品名称
    var money = $.trim($('#productPrice').val());//产品售价
    var scoreMoney = $.trim($('#scoreMoney').val());//业绩金额
    var scoreConvertRatio = $.trim($('#scoreConvertRatio').val());//业绩换算比例
    var royaltyMoney = $.trim($('#royaltyMoney').val());//应发放提成
    var customerProductId = $.trim($('#productName').val());//产品id
    var orderDetailId = $.trim($('#orderDetailId').val());//子订单ID
    var productOrderDetailType = $.trim($('#productOrderDetailType').val());//产品类型
    var finishOrderProductId = $.trim($('#finishOrderProductId').val());//产品号


    if (!productName) {
        promptInfo("产品名称不能为空!");
        return;
    }
    if (!money) {
        promptInfo("产品售价不能为空!");
        return;
    }
    if (!scoreMoney) {
        promptInfo("业绩金额不能为空!");
        return;
    }
    if (!scoreConvertRatio) {
        promptInfo("业绩换算比例不能为空!");
        return;
    }
    if (!royaltyMoney) {
        promptInfo("应发放提成不能为空!");
        return;
    }
    var jsonData={
        productOrderId:productOrderId, //订单id
        productName:productName, //产品名称
        productFinalPrice:money, //产品成交价
        scoreMoney:scoreMoney, //业绩金额
        scoreConvertRatio:scoreConvertRatio, //业绩换算比例
        royaltyMoney:royaltyMoney, //应发放提成
        productId:customerProductId, //产品id
        orderDetailId:orderDetailId, //子产品ID
        productType:productOrderDetailType, //产品类型
        finishOrderProductId:finishOrderProductId,
    }
    $.ajax({
        url: '/sendRoyalty/addSendRoyalty',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success:function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                //页面跳转赋值
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                window.location.reload();
                                /*closeTab(navTab);
                                openTab("回款记录","/front/receiptManager/userReceiptRecord");*/
                                //delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            }else {
                $.alert(data.message);
            }
        },
        error: (function (res) {
            $.alert("保存失败");
        })
    })





}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

// 自定义添加操作
function operateFormatter(value, row, index) {
    //\'' + row.returnMoneyId + '\',
    var result = '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + row.customerProductId + '\', \'' + row.productName + '\',\'' + row.money + '\')"><i class=""></i>删除产品</button>';
    return result;
}
function btnOperate() {
    $(".disabled-off").attr("disabled",false)
}

// 自定义编辑操作
function enterPayMent(value, row, index) {
    var result = '<button type="button" data-toggle="modal" data-target="#addInputMoney" class="btn btn-default" onclick="btnEdit(\''+row.customerProductId+'\',\''+row.productName+'\',\''+row.money+'\',\''+row.orderDetailId+'\',\''+row.productOrderDetailType+'\',\''+row.scoreMoney+'\',\''+row.scoreConvertRatio+'\',\''+row.royaltyMoney+'\',\''+row.finishOrderProductId+'\')"><i class=""></i>编辑</button>';
    return result;
}
function btnEdit(customerProductId,productName,money,orderDetailId,productOrderDetailType,scoreMoney,scoreConvertRatio,royaltyMoney,finishOrderProductId) {
    $(".disabled-off").attr("disabled",true)
    $("#productName").val(productName) //产品名称
    $("#productPrice").val(money) //产品成交价
    $("#orderDetailId").val(orderDetailId) //
    $("#finishOrderProductId").val(finishOrderProductId) //产品号
    $("#productOrderDetailType").val(productOrderDetailType) //产品类型
    if ("null" ==scoreMoney){
        $('#scoreMoney').val("")//业绩金额
    }else {
        $('#scoreMoney').val(scoreMoney)//业绩金额
    }
    if ("null" ==scoreConvertRatio){
        $('#scoreConvertRatio').val("")//业绩换算比例
    }else {
        $('#scoreConvertRatio').val(scoreConvertRatio)//业绩换算比例
    }
    if ("null" ==royaltyMoney){
        $('#royaltyMoney').val("")//应发放提成
    }else {
        $('#royaltyMoney').val(royaltyMoney)//应发放提成
    }
    // $("#customerProductId").val(customerProductId) //产品id
    //回显产品
    getOrderProductList(customerProductId);

}
function hideInput() {
    $(".disabled-off").attr("disabled",false)
    // window.location.reload();
    $('#productName').val('') //产品名称
    $('#productPrice').val('') //产品售价
    $('#scoreMoney').val('') //业绩金额
    $('#scoreConvertRatio').val('') //业绩换算比例
    $('#royaltyMoney').val('') //应发放提成
    // $royaltyMoneyTableList.bootstrapTable('refresh');
}